<?php

class FrontendAction extends PiscesAction
{

    public function __construct()
    {
        parent::__construct();
        $this->data['menu'] = 'index';
    }

    public function beforeExecute()
    {
        parent::beforeExecute();
        //修改记录 2011.3.27
        $this->data['site'] = array(
            'template' => 'default',
            'site_name' => '正品商城',
            'beian' => '你的备案号',
            'email' => '你的Email',
            'qq' => '你的QQ',
            'wangwang' => '你的旺旺',
            'tongji' => '<script type="text/javascript" src="http://js.tongji.linezing.com/2239773/tongji.js"></script><noscript><a href="http://www.linezing.com"><img src="http://img.tongji.linezing.com/2239773/tongji.gif"/></a></noscript>',
            'id_key' => 'xz',
        );
        //$this->data['site'] = C('SettingService')->get('site_setting', true);
        // $this->data['return'] = C('SettingService')->get('return_setting', true);

        $apiSetting = C('SettingService')->get('api_setting', true);

        $this->data['taobao']['pid'] = $apiSetting['taobao_api_pid'];

        $this->data['cf'] = C('CommonFunction');

        $this->data['domain'] = $this->context->server('SERVER_NAME');
        //$this->data['menuList'] = C('MenuService')->getList();
        //$this->data['config'] = C('SettingService')->get('config_setting', true);
        $this->data['config'] = array(
            'system' => array
                (
                'encode' => 'UTF-8',
                'ipcheck' => '',
                'autoadmit' => 0,
            ),
            'search8' => array(
                'enable' => 1,
                'keyword' => '女装,手机,平板电脑,减肥药,化妆品',
            )
        );

        $this->data['clickUrl'] = C('LtUrl')->generate('Default', 'Click', array('id' => 'defaultId'));

        $this->data['isRobot'] = $this->isRobot();

        $this->viewDir = $this->viewDir . $this->data['site']['template'] . '/';

        //$this->data['loginUrl']	= $this->getLoginUrl();
        //$this->getUserInfo();
    }

    public function getLoginUrl()
    {
        return $this->data['cf']->getLoginUrl() . base64_encode('http://' . $this->data['domain'] . C('LtUrl')->generate('Default', 'Index'));
    }

    public function getSeoStr($str, $replace)
    {
        foreach ($replace as $k => $v)
        {
            $str = str_replace('{' . $k . '}', $v, $str);
        }
        return $str;
    }

    public function getSearchKeyword()
    {
        $fromUrl = $this->context->referer('', '', false);
        $sea1 = "baidu.com"; //wd=
        $sea2 = "google.com"; //q=
        $sea3 = "soso.com"; //w=
        $sea4 = "sogou.com"; //w=
        $keyword = "";
        $exist1 = preg_match("/\b{$sea1}\b/", $fromUrl);
        $exist2 = preg_match("/\b{$sea2}\b/", $fromUrl);
        $exist3 = preg_match("/\b{$sea3}\b/", $fromUrl);
        $exist4 = preg_match("/\b{$sea4}\b/", $fromUrl);
        if ($exist1)
        {
            $source = $fromUrl;
            $start = stripos($fromUrl, 'wd=');
            $source = substr($source, $start + strlen('wd='));
            $start = stripos($source, '&');
            if ($start > 0)
            {
                $start = stripos($source, '&');
                $keyword = substr($source, 0, $start);
            }
            else
            {
                $keyword = substr($source, 0);
            }
            $keyword = urldecode($keyword);
            $keyword = iconv('GBK', 'UTF-8', $keyword);
        }
        elseif ($exist2)
        {
            $source = $fromUrl;
            $start = stripos($source, 'q=');
            $source = substr($source, $start + strlen('q='));
            $start = stripos($source, '&');
            if ($start > 0)
            {
                $start = stripos($source, '&');
                $keyword = substr($source, 0, $start);
            }
            else
            {
                $keyword = substr($source, 0);
            }
            $keyword = urldecode($keyword);
        }
        elseif ($exist3)
        {
            $source = $fromUrl;
            $start = stripos($source, 'w=');
            $source = substr($source, $start + strlen('w='));
            $start = stripos($source, '&');
            if ($start > 0)
            {
                $start = stripos($source, '&');
                $keyword = substr($source, 0, $start);
            }
            else
            {
                $keyword = substr($source, 0);
            }
            $keyword = urldecode($keyword);
            $keyword = iconv('GBK', 'UTF-8', $keyword);
        }
        elseif ($exist4)
        {
            $source = $fromUrl;
            $start = stripos($source, 'query=');
            $source = substr($source, $start + strlen('query='));
            $start = stripos($source, '&');
            if ($start > 0)
            {
                $start = stripos($source, '&');
                $keyword = substr($source, 0, $start);
            }
            else
            {
                $keyword = substr($source, 0);
            }
            $keyword = urldecode($keyword);
            $keyword = iconv('GBK', 'UTF-8', $keyword);
        }

        $keyword = str_replace("\\", '', str_replace("'", '', $keyword));
        return $keyword;
    }

    public function isRobot()
    {
        if (empty($_SERVER['HTTP_USER_AGENT']))
        {
            return false;
        }

        $searchEngineBot = array(
            'googlebot',
            'mediapartners-google',
            'baiduspider',
            'msnbot',
            'yodaobot',
            'yahoo! slurp;',
            'yahoo! slurp china;',
            'iaskspider',
            'sogou web spider',
            'sogou push spider',
            'sosospider',
        );

        $spider = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach ($searchEngineBot as $key => $value)
        {
            if (strpos($spider, $value) !== false)
            {
                return true;
            }
        }
        return false;
    }

    private function getUserInfo()
    {
        //������cookie��ȡ��½��Ϣ
        $authCode = C('LtCookie')->getCookie('user_auth');
        if ($authCode)
        {
            list($id, $nick, $username, $expire) = explode("\t", $authCode);
            $userService = C('UserService');
            $user = $userService->get($id);
            if ($user && $user['taobao_nick'] == $nick)
            {
                if (empty($user['logo']))
                {
                    $user['logo'] = $this->data['baseurl'] . 'images/avatar-120.png';
                }
                $this->data['user'] = $user;
                //����cookie
                if ($expire - time() < 600)
                {
                    $expire = time() + 1200;
                    $authCode = $user['id'] . "\t" . $user['taobao_nick'] . "\t" . $user['username'] . "\t" . $expire;
                    C("LtCookie")->setCookie('user_auth', $authCode, $expire);
                }
            }
            else
            {
                $this->data['user'] = '';
                C('LtCookie')->delCookie('auth');
            }
        }

        if ($user)
        {
            if ($user['username'] == '' && !($this instanceof UserSetupAction || $this instanceof UserSaveSetupAction))
            {
                header("Location: " . C('LtUrl')->generate('User', 'Setup'));
                return false;
            }
            return $user;
        }

        $topParams = $this->context->get('top_parameters');
        $topSign = $this->context->get('top_sign');
        $topSession = $this->context->get('top_session');
        if (empty($topParams) || empty($topSign) || empty($topSession))
        {
            return false;
        }
        $tmp = file_get_contents('http://tool.taozhangmen.net/index.php?module=user&action=checklogin&top_parameters=' . base64_encode($topParams) . '&top_sign=' . base64_encode($topSign) . '&top_session=' . base64_encode($topSession));
        if ($tmp != 'success')
        {
            return false;
        }
        $str = base64_decode($topParams);
        $tmp = explode('&', $str);
        $info = array();
        foreach ($tmp as $v)
        {
            $tt = explode('=', $v);
            if (count($tt) == 2)
            {
                $info[$tt[0]] = $tt[1];
            }
        }
        $userName = iconv('GBK', 'UTF-8', $info['visitor_nick']);
        if (empty($userName))
        {
            return false;
        }

        //����ݿ���ȡ�û�
        $userService = C('UserService');
        $user = $userService->getUserByTaobaoNick($userName);
        if (!$user)
        {
            //�ӿ���ƽ̨��ȡ�û������浽��ݿ���
            $user = C('UserService')->getUserFromTaobao($userName, $topSession);
            if ($user)
            {
                $userInfo = array();
                $userInfo['taobao_id'] = $user['user_id'];
                $userInfo['taobao_nick'] = $user['nick'];
                $userInfo['username'] = '';
                $userInfo['promoted'] = $user['promoted_type'] == 'authentication' ? 1 : 0;
                $userInfo['alipay_account'] = $user['alipay_account'];
                $userInfo['email'] = $user['email'];

                $id = $userService->add($userInfo);
                if ($id > 0)
                {
                    $user = $userService->get($id);
                }
            }
        }

        if ($user)
        {
            //���浽cookie��20��������Ч
            $expire = time() + 1200;
            $authCode = $user['id'] . "\t" . $user['taobao_nick'] . "\t" . $user['username'] . "\t" . $expire;
            C("LtCookie")->setCookie('user_auth', $authCode, $expire);

            if ($user['username'] == '' && !($this instanceof UserSetupAction || $this instanceof UserSaveSetupAction))
            {
                header("Location: " . C('LtUrl')->generate('User', 'Setup'));
                return false;
            }

            if (empty($user['logo']))
            {
                $user['logo'] = $this->data['baseurl'] . 'images/avatar-120.png';
            }
            $this->data['user'] = $user;
        }

        return $user;
    }

    protected function getProductIdFromUrl($url)
    {
        //������
        $domain = $this->data['domain'];
        $tmp = parse_url($url);
        $urlDomain = $tmp['host'];
        $query = $tmp['query'];
        //��վ�ģ�����Ƿ�����Ʒ����ҳ
        if (strtolower($domain) == strtolower($urlDomain))
        {
            $pre = 'Default-View-id';
            $pre2 = 'Default/View/id';
            $shotCut = C('LtConfig')->get("router.shot_cut");
            if (!empty($shotCut))
            {
                if (array_key_exists($pre, $shotCut))
                {
                    $pre = $shotCut[$pre];
                }
                if (array_key_exists($pre2, $shotCut))
                {
                    $pre = $shotCut[$pre2];
                }
            }
            $p = strpos($tmp['path'], '/' . $pre);
            if ($p !== false)
            {
                $path = substr($tmp['path'], $p + strlen($pre) + 2);
                $routingTable = C('LtConfig')->get("router.routing_table");
                $productId = str_replace($routingTable['postfix'], '', $path);
                if (!is_numeric($productId))
                {
                    $productId = base64_decode($productId);
                    $tmp = explode('_', $productId);
                    $productId = $tmp[0];
                }
                return $productId;
            }
        }
        //��վ��α��̬ģʽ�����Ա�����ҳURL
        if (preg_match('~id=([^&]*)~', $query, $m))
        {
            $productId = $m[1];
            if (!is_numeric($productId))
            {
                $productId = base64_decode($productId);
                $tmp = explode('_', $productId);
                $productId = $tmp[0];
            }
            return $productId;
        }

        return 0;
    }

}